from django.shortcuts import render, redirect
from .models import Book
from datetime import datetime
from django.db.models import Q

def book_list(request):
    search_query = request.GET.get('search', '')
    if search_query:
        books = Book.objects.filter(
            Q(title__icontains=search_query) |
            Q(author__icontains=search_query)
        )
    else:
        books = Book.objects.all()
    return render(request, 'books/book_list.html', {'books': books})

def add_book(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        author = request.POST.get('author')
        publish_date = request.POST.get('publish_date')
        
        Book.objects.create(
            title=title,
            author=author,
            publish_date=publish_date
        )
        return redirect('book_list')
    return render(request, 'books/add_book.html')
